/**
 * Caesar
 * 
 * 05/12/2013
 * 
 * Copyright GPL
 */
package com.jtmproject.javiertejedor.cyphers;

/**
 * this class encrypts and decrypts with Caesar Cypher
 * @author Javier Tejedor
 * @thanks http://rosettacode.org/wiki/Caesar_cipher
 */
public class CaesarCypher implements Encryption {
	
	private static final int NUMBER_TO_OFFSET = 12;
	private int offset = NUMBER_TO_OFFSET;

	/* (non-Javadoc)
	 * @see 
	 * com.jtmproject.javiertejedor.cyphers.Encryption#encrypt(java.lang.String)
	 */
	@Override
	public String encrypt(String textToEncrypt) {
		offset = offset % 26 + 26;
		StringBuilder encoded = new StringBuilder();
		for (char i : textToEncrypt.toLowerCase().toCharArray()) {
			if (Character.isLetter(i)) {
				int j = (i - 'a' + offset) % 26;
				encoded.append((char) (j + 'a'));
			} else {
				encoded.append(i);
			}
		}
		offset = NUMBER_TO_OFFSET;
		return encoded.toString();
	}

	/* (non-Javadoc)
	 * @see 
	 * com.jtmproject.javiertejedor.cyphers.Encryption#decrypt(java.lang.String)
	 */
	@Override
	public String decrypt(String textoToDecrypt) {
		offset = -NUMBER_TO_OFFSET;
		return encrypt(textoToDecrypt);
	}

}
